/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: Subject
 * Author:   zengjian
 * Date:     2018/7/27 10:47
 * Description: 行为主题
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.principle.pattern33.a020.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 〈行为主体〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/7/27 10:47
 */
public class Subject {

    private String state;

    private List<Listener> listeners;

    public Subject() {
    }

    public boolean addListener(Listener listener) {
        if (listeners == null) {
            listeners = new ArrayList<>();
        }
        return listeners.add(listener);
    }

    public void setState(String state) {
        this.state = state;
        notify(listeners);
    }

    private void notify(List<Listener> listeners) {
        for (Listener listener : listeners) {
            listener.receive(state);
        }
    }
}